<?php
/**
 * Created by PhpStorm.
 * User: 雨寒
 * Date: 2018/12/19
 * Time: 下午3:21
 */

namespace app\admin\controller;

use think\Db;
use app\common\model\Order as commonorder;
use app\common\model\Message;

class Order extends Common
{
    //订单列表
    public function order_data($status)
    {
        $this->assign('status', $status);
        if ($status == 'all') {
            $this->templateTitle('全部订单');
            $where['or.id'] = ['gt', 0];
        } elseif ($status == 'nopay') {
            $this->templateTitle('未支付订单');
            $where['or.order_status'] = 0;
        } elseif ($status == 1) {
            $this->templateTitle('待发货订单');
            $where['or.order_status'] = 1;
        } elseif ($status == 2) {
            $this->templateTitle('待收货订单');
            $where['or.order_status'] = 2;
        } elseif ($status == 3) {
            $this->templateTitle('已完成订单');
            $where['or.order_status'] = ["in", [3,5]];
        } elseif ($status == -1) {
            $this->templateTitle('取消订单');
            $where['or.order_status'] = 4;
        }
        //搜索条件-用户
        $user_condition = request()->param("user_condition");
        $this->assign("user_condition", $user_condition);
        if ($user_condition) {
            $where["us.nick_name|us.mobile|us.id"] = $user_condition;
        }
        //搜索条件-订单
        $or_condition = request()->param("or_condition");
        $this->assign("or_condition", $or_condition);
        if ($or_condition) {
            $where["or.id|or.order_sn"] = $or_condition;
        }

        //搜索条件-注册时间
        if (request()->has("time_range")) {
            //解析时间
            $timeRange = request()->param("time_range");
            $timeRange = explode(" ~ ", $timeRange);
            //模板渲染值
            $this->assign("range_start", ["time_range" => $timeRange[0]]);
            $this->assign("range_end", ["time_range" => $timeRange[1]]);

            $where['or.create_time'] = ["BETWEEN", [strtotime($timeRange[0] . " 00:00:00"), strtotime($timeRange[1] . " 23:59:59")]];

        } else {
            //模板渲染值
            $this->assign("range_start", ["time_range" => '2018-01-01']);
            $this->assign("range_end", ["time_range" => date("Y-m-d")]);
        }

        //获取订单列表
        $list = Db::name("order")
            ->alias('or')
            ->join('__USER__ us', 'us.id=or.uid', 'LEFT')
            ->where($where)
            ->order("or.id DESC")
            ->field('or.*,us.nick_name as nick_name,us.mobile as mobile')
            ->paginate(10);

        $this->assign("list", $list);
        $all_money = Db::name("order")
            ->alias('or')
            ->join('__USER__ us', 'us.id=or.uid', 'LEFT')
            ->where($where)
            ->value('sum(or.total_price)');
        $this->assign("all_money", $all_money);
        return $this->fetch('order/index');
    }

    /*全部订单*/
    public function statusAll()
    {
        return $this->order_data('all');
    }

    /*未支付订单*/
    public function status0()
    {
        return $this->order_data('nopay');
    }

    /*待发货订单*/
    public function status1()
    {
        return $this->order_data('1');
    }

    /*待收货订单*/
    public function status2()
    {
        return $this->order_data('2');
    }

    /*已完成订单*/
    public function status3()
    {
        return $this->order_data('3');
    }

    /*已取消订单*/
    public function status_1()
    {
        return $this->order_data('-1');
    }
    /*确认付款*/
    public function confirm_pay()
    {
        $orderid = input('id');
        $order = Db::name('order')
            ->where('id', $orderid)
            ->find();
        if (empty($order)) {
            $this->ajaxError("不存在此订单！");
        }
        if ($order['order_status'] != 0) {
            $this->ajaxError("此订单的状态不可以确认付款！");
        }
        /*确认付款需要生成结算单*/
        $data = array(
            'pay_status' => 1,
            'pay_type' => 0,
            'pay_time' => time(),
            'pay_money'=>$order["money"],
            'order_status'=>1,
            "update_time"=>time()
        );
        Db::name('order')
            ->where('id', $orderid)
            ->update($data);
        Message::admin_log(0, "后台确认付款订单id:" . $orderid);
        $this->ajaxSuccess("确认付款成功！");
    }

    /*订单详情*/
    public function order_info()
    {
        $orderid = input('id');

        /*订单信息*/
        $orderinfo = Db::name('order')
            ->alias('o')
            ->join("__USER__ u", "o.uid=u.id")
            ->where('o.id', $orderid)
            ->field('o.*,u.nick_name as nick_name,u.mobile as mobile')
            ->find();
        /*商品信息*/
        $ordergoods = Db::name('order_goods')
            ->where('order_sn', $orderinfo["order_sn"])
            ->select();
        $this->layoutModal();
        $this->assign('orderinfo', $orderinfo);
        $this->assign('ordergoods', $ordergoods);
        return $this->fetch();
    }

    /*删除订单*/
    public function remove()
    {
        $orderid = input('id');
        if (empty($orderid)) {
            $this->ajaxError("参数错误！");
        }
        $order = Db::name('order')
            ->where('id', $orderid)
            ->find();
        if (!$order) {
            $this->ajaxError('无此订单或订单未取消禁止删除');
        }
        /*删除订单*/
        Db::name('order')
            ->where('id', $orderid)
            ->delete();
        /*删除订单商品*/
        Db::name('order_goods')
            ->where('order_sn', $order["order_sn"])
            ->delete();
        Message::admin_log(0, "后台删除订单id:" . $orderid);
        $this->ajaxSuccess("删除成功！");
    }

    /*确认收货*/
    public function confirm_receive()
    {
        if (request()->isAjax()) {
            $order_id = input('id');
            $uid = input('uid');
            try {
                Message::admin_log(0, "后台确认收货订单id:" . $order_id);
                \app\common\model\Order::orderReceive($uid, $order_id);
                $this->ajaxSuccess("操作成功");
            } catch (\Exception $exception) {
                $this->ajaxError($exception->getMessage());
            }
        }
    }

    /**
     * 订单发货
     */
    public function send_order()
    {
        $order_id = input("order_id");
        if(request()->isAjax()){
            $data = [
                "update_time"=>time(),
                "order_status"=>2,
                "send_time"=>time(),
                "send_sn"=>input("send_sn"),
                "send_company"=>input("send_company")
            ];
            \db("order")->where("id", $order_id)->update($data);
            $this->ajaxSuccess("发货成功");
        }
        $this->layoutModal();
        $this->assign("order_id", $order_id);
        return $this->fetch("send_order");
    }

    /**
     * 订单导出
     */
    public function order_export()
    {
        $status = input("status");
        if ($status == 'all') {
            $where['or.id'] = ['gt', 0];
        } elseif ($status == 'nopay') {
            $where['or.order_status'] = 0;
        } elseif ($status == 1) {
            $where['or.order_status'] = 1;
        } elseif ($status == 2) {
            $where['or.order_status'] = 2;
        } elseif ($status == 3) {
            $where['or.order_status'] = ["in", [3,5]];
        } elseif ($status == -1) {
            $where['or.order_status'] = 4;
        }
        //搜索条件-用户
        $user_condition = request()->param("user_condition");
        if ($user_condition) {
            $where["us.nick_name|us.mobile|us.id"] = $user_condition;
        }
        //搜索条件-订单
        $or_condition = request()->param("or_condition");
        if ($or_condition) {
            $where["or.id|or.order_sn"] = $or_condition;
        }
        //搜索条件-注册时间
        if (request()->has("time_range")) {
            //解析时间
            $timeRange = request()->param("time_range");
            $timeRange = explode(" ~ ", $timeRange);
            $where['or.create_time'] = ["BETWEEN", [strtotime($timeRange[0] . " 00:00:00"), strtotime($timeRange[1] . " 23:59:59")]];
        }

        //获取订单列表
        $list = Db::name("order")
            ->alias('or')
            ->join('__USER__ us', 'us.id=or.uid', 'LEFT')
            ->where($where)
            ->order("or.id DESC")
            ->field('or.*,us.nick_name as nick_name,us.mobile as mobile')
            ->select();
        foreach ($list as &$item){
            $good_list = \db("order_goods")->where("order_sn", $item["order_sn"])->select();
            $info = "";
            foreach ($good_list as $g){
                $info .= $g["title"]."-".$g["spec_title"]."     ".$g["num"]."     ".$g["price"]."\n";
            }
            $item["good_info"] = $info;
        }
        $header = [
            "订单编号",
            "商品金额",
            "运费",
            "总价",
            "积分抵扣",
            "实际支付金额",
            "买家信息",
            "收获信息",
            "商品信息"
        ];
        $body = [];
        foreach ($list as $val){
            $temp = [
                $val["order_sn"],
                $val["goods_price"],
                $val["dispatch_price"],
                $val["total_price"],
                $val["score_fee"],
                $val["money"],
                "昵称：".$val["nick_name"]."\n"."手机号：".$val["mobile"],
                "收货地址：".$val["send_address"]."\n"."联系人姓名：".$val["send_name"]."\n"."联系人电话：".$val["send_mobile"],
                $val["good_info"]
            ];
            $body[] = $temp;
        }
        echo \Excel::export($header, $body);
        exit();
    }

}